package com.daji.io_nio.selector;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws Exception{
        //1、获取通道，绑定主机和端口号
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8000));

        //2、切换到非阻塞模式
        socketChannel.configureBlocking(false);
        //3、创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        //4、写入buffer数据
        System.out.println("请在控制台输入数据");
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String str = scanner.next();

            byteBuffer.put(str.getBytes(StandardCharsets.UTF_8));
            //5、模式切换
            byteBuffer.flip();
            //6、写入通道
            socketChannel.write(byteBuffer);

            //7、关闭
            byteBuffer.clear();
        }

    }
}
